﻿using System;
using System.Collections.Generic;
using System.Text;
using Conusic;

namespace MusicPage
{
    internal delegate void FileSongDownload(AudioRecord record);

    internal delegate void FileSongFail(AudioRecord record, Exception ext);

    internal delegate void FileSongProgress(AudioRecord record, long downloadKb, long totalKb);

    /// <summary>
    /// mediator for connect gui application events and commands from conusic api
    /// </summary>
    internal class DownSong : IDownloadSongCommand
    {
        public event FileSongDownload OnSongDownload;
        public event FileSongFail OnDownloadFail;
        public event FileSongProgress OnProgress;

        private DateTime lastUpdateTime = DateTime.MinValue;

        // update every 0.5 seconds
        private static readonly TimeSpan UpdateProgress = new TimeSpan(0, 0, 0, 0, 500);

        private readonly AudioRecord record;

        public DownSong(AudioRecord record)
        {
            this.record = record;
        }

        public void Success()
        {
            OnSongDownload(record);
        }

        public void Fail(Exception ext)
        {
            OnDownloadFail(record, ext);
        }

        public void ProgressExecute(long downloadedKb, long totalKb)
        {
            if (DateTime.Now - lastUpdateTime > UpdateProgress)
            {
                OnProgress(record, downloadedKb, totalKb);
                lastUpdateTime = DateTime.Now;
            }
        }
    }
}